const model = require('../model/LogoModel')
let {PORT, SUCCESS_RESPONSE} = require('../config/index')
let fs = require('fs')
const {FAIL_RESPONSE} = require("../config");

// 获取登录logo
exports.getLogoInfo = async (req, res) => {
    let result = await model.getLogoInfo()
    res.json(SUCCESS_RESPONSE(result))
}

// 上传登录logo图片
exports.addLogoImg = async (req, res) => {
    // 判断是否有文件上传
    if (req.file) {
        // 进行文件的重命名即可 fs.rename
        let {originalname, destination, filename} = req.file
        let dotIndex = originalname.lastIndexOf('.')
        let ext = originalname.substring(dotIndex)
        let oldPath = `${destination}${filename}`
        let newPath = `${destination}${filename}${ext}`
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                throw err
            }
            res.json({
                msg: '上传文件成功',
                data: {path: `${newPath}`, server_url: `http://127.0.0.1:${PORT}/`},
                code: '00000',
            })
        })
    } else {
        res.json({msg: '没有文件', data: {}, code: '00089'})
    }
}

// 设置登录logo图片
exports.setLogoImg = async (req, res) => {
    let {logo_img} = req.body
    let result = await model.updateLogoImg(logo_img)
    if (result.affectedRows > 0) {
        return res.json(SUCCESS_RESPONSE({},'更新Logo成功'))
    }else {
        return res.json(FAIL_RESPONSE({},'更新Logo失败','00020'))
    }
}

// 设置登录logo标题
exports.setLogoTitle = async (req, res) => {
    let {logo_title} = req.body
    let result = await model.updateLogoTitle(logo_title)
    if (result.affectedRows > 0) {
        return res.json(SUCCESS_RESPONSE({},'更新标题成功'))
    }else {
        return res.json(FAIL_RESPONSE({},'更新标题失败','00021'))
    }
}